﻿#region License
/*
The MIT License

Copyright (c) 2008 Sky Morey

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System;
using System.Threading;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices.ComTypes;
using Native_.DirectShow;
namespace Capture.DirectShow
{
    /// <summary>
    /// FrameCapturer
    /// </summary>
    public partial class FrameCapturer : IDisposable
    {
        private ManualResetEvent _stopEvent = new ManualResetEvent(false);
        private Thread _workerThread;
        private IFrameInfo _frameInfo;
        private DeviceInfo _device;
        private bool _dispatchOnWorkerThread;
        private bool _started;

        /// <summary>
        /// BehaviorVectorMask
        /// </summary>
        public enum BehaviorVectorMask
        {
            DispatchOnWorkerThread = 0x01
        }

        public FrameCapturer()
            : this(DeviceInfo.GetDefaultDevice()) { }
        public FrameCapturer(DeviceInfo device)
        {
            _device = device;
        }
        ~FrameCapturer() { Dispose(); }
        public virtual void Dispose()
        {
            if (_started)
                Stop();
            _stopEvent.Dispose(); _stopEvent = null;
            GC.SuppressFinalize(this);
        }

        public BitVector32 BehaviorVector = new BitVector32(); //(int)BehaviorVectorMask.DispatchOnWorkerThread);

        public IFrameInfo FrameInfo
        {
            get { return _frameInfo; }
            private set
            {
                if (value == null)
                    throw new ArgumentNullException("value");
                _frameInfo = value;
            }
        }

        private void WorkerThread(object start)
        {
            if (BehaviorVector[(int)BehaviorVectorMask.DispatchOnWorkerThread])
                _dispatchOnWorkerThread = true;
            FrameInfo = ((Func<IFrameInfo>)start)();
            var sampleGrabberCB = new SampleGrabberCB(FrameInfo, _dispatchOnWorkerThread);
            OnEnterWorkerThread();
            try
            {
                var graph = (Activator.CreateInstance(Type.GetTypeFromCLSID(Registry.FilterGraph)) as IGraphBuilder);
                var sourceObject = FilterInfo.CreateFilter(_device.Moniker);
                var sampleGrabber = (Activator.CreateInstance(Type.GetTypeFromCLSID(Registry.SampleGrabber)) as ISampleGrabber);
                var grabberObject = (sampleGrabber as IBaseFilter);
                graph.AddFilter(sourceObject, "source");
                graph.AddFilter(grabberObject, "grabber");
                // set media type for our grabber
                using (var mediaType = new AMMediaType())
                {
                    mediaType.MajorType = Registry.MediaTypes.Video;
                    mediaType.SubType = Registry.MediaSubTypes.RGB32;
                    sampleGrabber.SetMediaType(mediaType);
                    // and then connect device filter to out pin and grabber to in pin. then get capabilities of video received (this stuff comes from your web camera manufacturer)
                    if (graph.Connect(sourceObject.GetPin(PinDirection.Output, 0), grabberObject.GetPin(PinDirection.Input, 0)) >= 0)
                        if (sampleGrabber.GetConnectedMediaType(mediaType) == 0)
                            _frameInfo.SetProperties((VideoInfoHeader)Marshal.PtrToStructure(mediaType.FormatPtr, typeof(VideoInfoHeader)));
                    // out pin to grabber without buffering and callback to grabber object (this one will get all images from our source).
                    graph.Render(grabberObject.GetPin(PinDirection.Output, 0));
                    sampleGrabber.SetBufferSamples(false);
                    sampleGrabber.SetOneShot(false);
                    sampleGrabber.SetCallback(sampleGrabberCB, 1);
                    // dump output window
                    var wnd = (IVideoWindow)graph;
                    wnd.put_AutoShow(false); wnd = null;
                    // and run the controller
                    var control = (IMediaControl)graph;
                    control.Run();
                    //
                    if (_dispatchOnWorkerThread)
                    {
                        Dispatcher.Run();
                        //while (!WaitHandle.WaitAll(new WaitHandle[] { _stopSignal }, 10, true))
                        while (!_stopEvent.WaitOne(10, true))
                            Dispatcher.Run();
                        Dispatcher.ExitAllFrames();
                    }
                    else
                        while (!_stopEvent.WaitOne(0, true))
                            Thread.Sleep(10);
                    //
                    control.StopWhenReady();
                }
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex);
                Debug.WriteLine(ex);
                throw;
            }
            finally
            {
                // guaranteed exit
                OnExitWorkerThread();
            }
        }

        #region Threading

        public void Start(Func<IFrameInfo> start)
        {
            if (_device.Moniker == null)
                return;
            if (_started)
                throw new InvalidOperationException("CaptureAlreadyStarted");
            _workerThread = new Thread(new ParameterizedThreadStart(WorkerThread))
            {
                Name = "CapturerWorker",
                Priority = ThreadPriority.Highest,
                IsBackground = true,
            };
            _workerThread.SetApartmentState(ApartmentState.MTA);
            _workerThread.Start(start);
            _started = true;
        }

        public void Stop()
        {
            if (!_started)
                throw new InvalidOperationException("CaptureNotStarted");
            _stopEvent.Set();
#if DEBUG
            _workerThread.Join(); _workerThread = null;
#else
            _workerThread.Join(new TimeSpan(0, 0, 10)); _workerThread = null;
#endif
            _started = false;
        }

        public event EventHandler EnterWorkerThread;

        protected virtual void OnEnterWorkerThread()
        {
            var enterWorkerThread = EnterWorkerThread;
            if (enterWorkerThread != null)
                enterWorkerThread(this, EventArgs.Empty);
        }

        public event EventHandler ExitWorkerThread;

        protected virtual void OnExitWorkerThread()
        {
            var exitWorkerThread = ExitWorkerThread;
            if (exitWorkerThread != null)
                exitWorkerThread(this, EventArgs.Empty);
        }

        #endregion
    }
}
